﻿using System.Collections.Generic;
using Cms.Application.Admin.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class LocalesPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly ILocalesView _view;

        public LocalesPresenter(ILocalesView view)
            : this(view, new RepositoryFactory())
        {
        }

        public LocalesPresenter(ILocalesView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.Locales)
                _view.RedirectToPermissionDeniedPage();
        }

        public void Initialize()
        {
            SetLocales();
        }

        public void SetLocales()
        {
            _view.SetLocales(_administrator.CurrentSite.Locales);
        }
        
        public void DeleteLocale(int id)
        {
            Locale locale = LocaleRepository.GetLocale(id);
            if (locale.Site.DefaultLocale.ID != id)
            {
                PerformDelete(locale);
            }
            else if (_administrator.CurrentSite.Locales.Count > 1)
            {
                //Let user select an alternative default locale
                IList<Locale> replacements = new List<Locale>();
                foreach (Locale replacement in _administrator.CurrentSite.Locales)
                    if (replacement.ID != id)
                        replacements.Add(replacement);
                _view.SetReplacements(replacements, locale.GetTranslation(_view.Localization).Name);
            }
            else
            {
                _view.DisplayUnableToDeleteAlert(locale.GetTranslation(_view.Localization).Name);
            }
        }
        
        public void ReplaceAndDeleteLocale(int id, int replacementID)
        {
            Locale locale = LocaleRepository.GetLocale(id);
            Locale replacement = LocaleRepository.GetLocale(replacementID);
            _administrator.CurrentSite.DefaultLocale = replacement;
            SiteRepository.SaveSite(_administrator.CurrentSite);
            PerformDelete(locale);
        }
        
        private void PerformDelete(Locale locale)
        {
            LocaleRepository.DeleteLocale(locale);
            SiteRepository.SaveSite(_administrator.CurrentSite);
            SetLocales();
        }
    }
}